package com.orhon.smartcampus.modules.student.mutation;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.orhon.smartcampus.auth.JwtUtils;
import com.orhon.smartcampus.basicComponents.Result;
import com.orhon.smartcampus.modules.student.dao.ParentsDao;
import com.orhon.smartcampus.modules.student.entity.Parents;
import com.orhon.smartcampus.modules.student.gqlInputModel.GQLParentsInput;
import com.orhon.smartcampus.modules.student.inputMapper.ParentsInputMapper;
import com.orhon.smartcampus.modules.user.dao.TokenService;

import graphql.schema.DataFetcher;
import graphql.schema.DataFetchingEnvironment;

@Component
public class AddParentsMutation implements DataFetcher {



    @Autowired
    ParentsDao parentsDao;

    @Autowired
    TokenService tokenService;


    /**
     * 新增/修改届信息
     * editor : ths
     */
    @Override
    public Object get(DataFetchingEnvironment environment) throws Exception {

        //String token = (String) SecurityUtils.getSubject().getPrincipal();
        String token = tokenService.getSystemToken();
        Long schoolId = JwtUtils.getSchoolId(token);
      
        GQLParentsInput input = ParentsInputMapper.MAPPER.mapInput(environment.getArgument("inputData"));
        Parents parents = null;
        if (input.getId() != null){
        	parents = parentsDao.get(Parents.class , input.getId());
        	parents.setUpdatedAt(new Date());
        }
        else{
        	parents = new Parents();
        	parents.setCreatedAt(new Date());
        }
        if(input.getStudentId() != null){
        	parents.setStudentId(input.getStudentId());
        }
        if(input.getParentName() != null){
        	parents.setParentName(input.getParentName());
        }
        if(input.getRelation() != null){
        	parents.setRelation(input.getRelation());
        }
        if(input.getNation() != null){
        	parents.setNation(input.getNation());
        }
        if(input.getGender() != null){
        	parents.setGender(input.getGender());
        }
        if(input.getIdcard() != null){
        	parents.setIdcard(input.getIdcard());
        }
        if(input.getIsGuardian() != null){
        	parents.setIsGuardian(input.getIsGuardian());
        }
        if(input.getPostalAddress() != null){
        	parents.setPostalAddress(input.getPostalAddress());
        }
        if(input.getPicture()!= null){
        	parents.setPicture(input.getPicture());
        }
        if(input.getTelNumber() != null){
        	parents.setTelNumber(input.getTelNumber());
        }

        try{
        	parentsDao.saveOrUpdate(parents);
        }
        catch (Exception e){
        	System.out.println(e);
            return Result.error(500,""+e);
            
        }

        return parents;
    }
}

